package com.kaede.hayate.common.exception;

import com.kaede.hayate.config.ApplicationProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
public class RestBasicErrorController extends BasicErrorController {

    Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    private ApplicationProperties applicationProperties;

    final private ServerProperties serverProperties;

    public RestBasicErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
        super(errorAttributes, serverProperties.getError());
        this.serverProperties = serverProperties;
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request,
                isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = getStatus(request);

        String exceptionName = (String) body.get("exception");
        for(ExceptionMessage em : GlobalException.exceptionPool) {
            if(exceptionMatcher(exceptionName, em.getExceptionClass())) {
                body.put("errorCode",em.getErrorCode());
                body.put("errorMsg",em.getErrorMessage());
            }
        }
        Object tokenInvalid = request.getAttribute(applicationProperties.getTokenInvalidName());
        if(tokenInvalid != null && (Boolean)tokenInvalid){
            body.put("errorCode",-1);
            body.put("errorMsg","token无效或过期,请重新登录!");
        }

        return new ResponseEntity<>(body, status);
    }

    public boolean exceptionMatcher(String exceptionName,Class<?> clazz) {
        String ename = clazz.getName();
        if(ename.equals(exceptionName)) {
            return true;
        }
        return false;
    }
}
